package com.snj.visangedu;

import java.io.File;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.lib.NewsLib;
import com.snj.visangedu.news.New_NewsAdapter;
import com.snj.visangedu.news.News;

public class NewsFragment extends Fragment implements OnClickListener {
	private final String TAG = "NewsFragment";
		
	boolean isrunning = true;
	int newsid = 1;
	
	ListView mListNews = null;
	
	
	New_NewsAdapter _adapter = null;
	
	ListView lstv_news = null;
	
	public NewsFragment(int _newsid)
	{
		newsid = _newsid;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View root = inflater.inflate(R.layout.fragment_main_home,
				container, false);
		
		
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.d(TAG, "onActivityCreated");
		
		super.onActivityCreated(savedInstanceState);
		init_widget();
	}
	
	private void init_widget() {
		View view = getView();
//		mTxtCourseName = (TextView)
//				view.findViewById(R.id.todayplan_balancecoach_txt_coursename);
		
		
		
		lstv_news = (ListView)view.findViewById(R.id.news_list_news);
		
		_adapter = new New_NewsAdapter(getActivity(), R.layout.list_news, NewsLib.newsloader[newsid].GetNewsArray(), newsid);
		lstv_news.setAdapter(_adapter);
		_adapter.notifyDataSetChanged();
		
		
		
		
		lstv_news.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				//Log.d(tag, "link : " + Global.mNews.get(position).GetLink());
				_adapter.SetList(NewsLib.newsloader[newsid].GetNewsArray());
				_adapter.notifyDataSetChanged();
				
				Intent contentintent = new Intent(getActivity(), ContentActivity.class);
				
				contentintent.putExtra("newsid", newsid);
				
				if(position > 0)
				{
					contentintent.putExtra("prev", NewsLib.newsloader[newsid].GetNewsArray().get(position - 1).GetNo());// Global.mNews.get(position-1).GetNo());
				}
				
				contentintent.putExtra("no", NewsLib.newsloader[newsid].GetNewsArray().get(position).GetNo());
				contentintent.putExtra("position", position);
				contentintent.putExtra("type", "1");
				
				
				if(position < (NewsLib.newsloader[newsid].GetNewsArray().size() - 1))
				{
					contentintent.putExtra("next", NewsLib.newsloader[newsid].GetNewsArray().get(position+1).GetNo());
				}
				
				Log.d(TAG, "No : " + NewsLib.newsloader[newsid].GetNewsArray().get(position).GetNo());
				startActivity(contentintent);
			}
		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		//NewsLib.LoadNews(newsid, 5);

		new AsyncTask<String, String, String>() {

			String tag = "InitNews";
			
			
			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				
				Log.d(tag, "load newssssS");
				
				String currentpath = Global.ex_storage + "/visangedu/";
				String filename = "";
				
				
				while(NewsLib.IsLoadingNews)
				{
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					Log.d(tag, "loading...");
				}
				
				//for(int i=0; i<1; i++)
				{
					currentpath = Global.ex_storage + "/visangedu/news" + params[0] + "/"; 
					ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
					postParameters.add(new BasicNameValuePair("type", "A"));
					postParameters.add(new BasicNameValuePair("begin", String.format("%d", NewsLib.newsloader[newsid].GetNewsArray().size())));
					postParameters.add(new BasicNameValuePair("count", params[2]));
					postParameters.add(new BasicNameValuePair("newsid",params[0]));
					
	            	String result = "";
	            	JSONObject resultobject = null;
	            	
	            	try {
	            		Log.d("LoadNews", "request : " + postParameters.toString());
						result = CustomHttpClient.executeHttpPost(Global.newsurl, postParameters);
						Log.d("LoadNews", "response : " + result);
						
						resultobject = new JSONObject(result);
						
						JSONArray newsarr = resultobject.getJSONArray("data");
						JSONObject newsobject = null;
						
						
						
						for(int j=0; j<newsarr.length(); j++)
						{
							newsobject = newsarr.getJSONObject(j);
							
							//Log.d(tag, newsobject.getString("no") + " : " + newsobject.getString("imgsrc"));
							
							filename = newsobject.getString("imgsrc").replace(".jpg", ".vnews").replace(".png", ".vnews");
							
							File file = new File(currentpath + filename);
							
							Bitmap newsimg = null;
							
							if(file.exists())
							{
								Log.d(tag, "1st : Load from local");
								newsimg = BitmapFactory.decodeFile(currentpath + filename);
							} 
							
							if(newsimg == null)
							{
								newsimg = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "newsimages" + params[0] + "/" + newsobject.getString("imgsrc"));
								Global.saveBitmaptoJpeg(newsimg, "visangedu/news" + params[0], filename);
								Log.d(tag, "Save : " + currentpath + filename);
								Log.d(tag, "Download : " + filename);
							}
							 
							//Log.d(tag, "No : " + newsobject.getString("no"));
							
							NewsLib.newsloader[newsid].Add(new News(newsobject.getString("no"), newsimg));
							
							
						} 
						
						
	            	}
	            	catch(Exception e)
	            	{
	            		e.printStackTrace();
	            	}
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				
				_adapter.notifyDataSetChanged();
			}
			
			
		}.execute(String.format("%d", newsid + 1), String.format("%d", NewsLib.newsloader[newsid].GetNewsArray().size()), String.format("%d", 5));
	}

	@Override
	public void onClick(View v) {
		
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		isrunning = false;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		ArrayList<News> nlist = NewsLib.newsloader[newsid].GetNewsArray();
		
		for(int i=0; i< nlist.size(); i++)
		{
			nlist.get(i).Clear();
		}
		
		_adapter.SetList(null);
	}
	
	
	
	
}
